package com.fillifesoft.magicHitter.manager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.fillifesoft.magicHitter.MagicHitter;
import com.fillifesoft.magicHitter.model.NumberVo;
import com.fillifesoft.magicHitter.model.ResultVo;
import com.fillifesoft.magicHitter.output.MybatisImpl;
import com.fillifesoft.magicHitter.output.Output;

public class RepositoryManager {
	
	public NumberVo[] repo;
	public int repoCount = 0;
	public Output output;
	
	public void init() {
		repo = new NumberVo[MagicHitter.REPO_LEN];
		for(int i=0; i<MagicHitter.REPO_LEN; i++) {
			repo[i] = new NumberVo(i+1);
		}
	}
	
	private NumberVo getNumber(int number) {
		for(int i=0; i<MagicHitter.REPO_LEN; i++) {
			if(number == repo[i].getNumber()) {
				return repo[i];
			}
		}
		return null;
	}
	
	private NumberVo getIndex(int index) {
		return repo[index];
	}
	
	private void setIndex(NumberVo vo, int idx) {
		repo[idx] = vo;
	}
	
	public void countNumber(int number) {
		NumberVo vo = getNumber(number);
		vo.addCount();
	}
	
	private void swap(int idx1, int idx2) {
		NumberVo tmp = getIndex(idx2);
		setIndex(getIndex(idx1), idx2);
		setIndex(tmp, idx1);
	}
	
	private void sort() {
		int idx = 0;
		while(true) {
			int maxIndex = idx;
			int maxValue = 0;
			for(int i=idx; i<MagicHitter.REPO_LEN; i++) {
				if(getIndex(i).getCount() > maxValue) {
					maxIndex = i;
					maxValue = getIndex(i).getCount();
				}
			}
			
			swap(idx, maxIndex);
			
			if(++idx >= MagicHitter.REPO_LEN) {
				break;
			}
		}
	}
	
	public void output() throws Exception {
		ResultVo result = generateResult();
		output = new MybatisImpl();
		output.print(result);
	}
	
	public ResultVo generateResult() throws Exception {
		sort();
		
		List<NumberVo> list = new ArrayList<NumberVo>();
		for(int i=0; i<MagicHitter.MAX_NUMBER_COUNT; i++) {
			list.add(repo[i]);
		}
		Collections.sort(list);
		
		ResultVo result = new ResultVo();
		for(int i=0; i<list.size(); i++) {
			switch(i) {
				case 0:
					result.setNum1(list.get(i).getNumber());
					break;
				case 1:
					result.setNum2(list.get(i).getNumber());
					break;
				case 2:
					result.setNum3(list.get(i).getNumber());
					break;
				case 3:
					result.setNum4(list.get(i).getNumber());
					break;
				case 4:
					result.setNum5(list.get(i).getNumber());
					break;
				case 5:
					result.setNum6(list.get(i).getNumber());
					break;
			}
		}
		
		return result;
	}
}
